package top.cmx.learn.thread.test2;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author cmx
 */
public class TestTryLock extends Thread {
    static Lock lock = new ReentrantLock();

    @Override
    public void run() {
        boolean isLocked = false;
        String currentThreadName = Thread.currentThread().getName();
        try {
            //5s的时间内始终尝试枷锁
            isLocked = lock.tryLock(5, TimeUnit.MILLISECONDS);
            System.out.println(currentThreadName + "-尝试枷锁：" + isLocked);
            if (isLocked) {
                Thread.sleep(20);
                System.out.println(currentThreadName + "-枷锁成功");
            } else {
                System.out.println(currentThreadName + "-枷锁失败");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (isLocked) {
                System.out.println(currentThreadName + "-解锁");
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        TestTryLock testTryLock1 = new TestTryLock();
        TestTryLock testTryLock2 = new TestTryLock();
        testTryLock1.setName("t1");
        testTryLock2.setName("t2");
        testTryLock1.start();
        testTryLock2.start();
    }
}
